package com.partybuilding.aspect;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.partybuilding.annotation.DataScope;
import com.partybuilding.domain.ResponseResult;
import com.partybuilding.domain.entity.AdminRole;
import com.partybuilding.domain.entity.Admintable;
import com.partybuilding.domain.entity.LoginUser;
import com.partybuilding.domain.entity.Usertable;
import com.partybuilding.enums.AppHttpCodeEnum;
import com.partybuilding.enums.DataScopeEnum;
import com.partybuilding.expection.SystemException;
import com.partybuilding.service.AdminRoleService;
import com.partybuilding.utils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.partybuilding.enums.DataScopeEnum.DATA_SCOPE_ALL;
// TODO: 2024/6/24 本页数据过滤逻辑因为底层数据库框架的变动,需要全部重新设计
/**
 * 数据过滤处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class DataScopeAspect
{
    @Autowired
    private AdminRoleService adminRoleService;
    @Pointcut("@annotation(com.partybuilding.annotation.DataScope)")
    public void pt(){

    }

    @Around("pt()")
    public Object doBefore(ProceedingJoinPoint point) throws Throwable
    {
        return handleDataScope(point);
    }

    protected Object handleDataScope(final ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前的用户
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser=(LoginUser) authentication.getPrincipal();
        Object result = null;
        //若当前登录用户不为空
        if (!Objects.isNull(loginUser))
        {

            //获取传入参数
            Object[] args = joinPoint.getArgs();
            //对最后一个参数进行修改，也就是查询范围，默认查询语句为空
            LambdaQueryWrapper<Usertable> queryWrapper= (LambdaQueryWrapper<Usertable>)args[args.length-1];

            // 如果是超级管理员(id为1)或者空，则不过滤数据,&& (loginUser.getAdmintable().==1L)
            if (Objects.isNull(loginUser.getAdmintable()) )
            {
                //TODO 如果有其余操作可以在此写明;
            }
            else//否则根据用户的权限修改QueryWrapper
            {
                queryWrapper=dataScopeFilter(loginUser);
                args[args.length-1]=queryWrapper;
            }

            result=joinPoint.proceed(args);
        }
        return result;
    }

    /**
     * 数据范围过滤
     *
     */
    public  LambdaQueryWrapper<Usertable> dataScopeFilter( LoginUser loginUser)
    {
        StringBuilder sqlString = new StringBuilder();
        //用于角色和作用权限的合并
        List<String> conditions = new ArrayList<String>();

        LambdaQueryWrapper<Usertable> queryWrapper=new LambdaQueryWrapper<>();
        // TODO: 2024/6/24 此处逻辑存在问题,需要联合查表
        AdminRole role=adminRoleService.getRoleById(loginUser.getAdmintable().getUser_id(),loginUser.getRoleId());
        //获取到该角色的权限范围
        // TODO: 2024/6/24 此处逻辑存在问题,需要重新修改
        Long dataScope =Long.getLong(role.getRole_id()) ;

        //若为全部权限，则过滤时不做处理
        if (DataScopeEnum.DATA_SCOPE_ALL.getValue() ==dataScope)
        {
            ;
        }
        //若为自定义权限，则.......
        else if (DataScopeEnum.DATA_SCOPE_CUSTOM.getValue() ==dataScope)
        {
            ;
        }
        // TODO: 2024/6/24 此处存在问题 
/*        //本部门数据权限,则在sql查询语句上添加管辖的支部id
        else if (DataScopeEnum.DATA_SCOPE_DEPT.getValue() ==dataScope)
        {
            queryWrapper.eq(Usertable::getPd_branchesid,loginUser.getAdmintable().getAuthorityPartyId());
        }
        //本部门和下属数据权限,则使用like语句前缀匹配id，并通过前缀索引来提高效率
        else if (DataScopeEnum.DATA_SCOPE_DEPT_AND_CHILD.getValue() ==dataScope)
        {
            queryWrapper.likeRight(Usertable::getPartyId,loginUser.getAdmintable().getAuthorityPartyId());
        }*/
        //自身权限,则啥都查不了,不返回值
        else if (DataScopeEnum.DATA_SCOPE_SELF.getValue() ==dataScope)
        {
            queryWrapper.eq(Usertable::getId,0);
        }
        return queryWrapper;
    }




}
